package com.good.domain.Utils;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.util.Random;

/**
 * MD5生成加密密码
 * salt:随机生成16位的字符串的盐
 * generatePwd:
 * 1. 盐+密码拼接生成32位md5加密密码
 * 2. 将32位密码和16位盐穿插拼接48位密码 作为密码入库 (密码+盐+密码)3位循环
 * verify:
 * 3. 根据原2中穿插方式,将16位盐和32位md密码取出
 * 4. 同样盐+密码拼接生成32位md5加密密码
 * 5.对比3中32位密码 == 4中生成的密码
 */
public class PasswordUtil {

    /**
     * 生成md5密码
     * @param password 密码字符串
     * @return 48位加密密码
     */
    public static String generatePwd(String password){
        Random r = new Random();
        StringBuilder sb = new StringBuilder(16);
        sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
        int len = sb.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sb.append("0");
            }
        }
        String salt = sb.toString();
        password = md5Hex(password + salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return new String(cs);
    }

    /**
     *
     * @param password 密码字符串
     * @param md5 加密后的密码字符串
     * @return 是否匹配 true/false
     */
    public static boolean verify(String password, String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
            cs2[i / 3] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);
        return md5Hex(password + salt).equals(new String(cs1));
    }

    /**
     * 从加密后的密码中获取十六进制字符串形式的MD5摘要
     */
    private static String md5Hex(String src) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bs = md5.digest(src.getBytes());
            return new String(new Hex().encode(bs));
        } catch (Exception e) {
            return null;
        }
    }
}
